package com.example.androidexp22


import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.jjoe64.graphview.GraphView
import com.jjoe64.graphview.GridLabelRenderer
import com.jjoe64.graphview.LabelFormatter
import com.jjoe64.graphview.Viewport
import com.jjoe64.graphview.series.DataPoint
import com.jjoe64.graphview.series.LineGraphSeries
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Calendar


class EventDetailsActivity : AppCompatActivity() {
    private lateinit var btnGoToCalendar: Button
    private lateinit var btnBeginTimePicker: Button
    private lateinit var btnEndTimePicker: Button
    private lateinit var tvBeginTime: TextView
    private lateinit var tvEndTime: TextView
    private var eventDataList: MutableList<DateChoose.Event>? = null
    private lateinit var graph: GraphView

    private fun showTimePicker(textView: TextView) { //选择日期并保存
        val calendar = Calendar.getInstance()
        val datePickerDialog = DatePickerDialog(
            this,
            { _, year, monthOfYear, dayOfMonth ->
                val selectedDate = "$dayOfMonth/${monthOfYear + 1}/$year"
                // 使用 parseAndFormatDate 函数转换日期格式
                val formattedDate = parseAndFormatDate(selectedDate)
                if (formattedDate != null) {
                    textView.text = formattedDate // 将转换后的日期显示在 TextView 中
                } else {
                    println("无法解析选择的日期")
                }
            },
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        )
        datePickerDialog.show()
    }
    private fun parseAndFormatDate(dateStr: String?): String? {   //格式转化
        if (dateStr == null) return null
        val inputFormat = SimpleDateFormat("dd/MM/yyyy") // 假设原始日期格式为"dd/MM/yyyy"
        return try {
            val date = inputFormat.parse(dateStr)
            SimpleDateFormat("yyyy-MM-dd").format(date) // 转换为目标格式"yyyy-MM-dd"
        } catch (e: ParseException) {
            println("日期转换错误: ${e.message}")
            null
        }
    }

//    private fun loadEventDataFromPreferences() {    //对接收到的数据进行结构化
//        val sharedPreferences = getPreferences(Context.MODE_PRIVATE)
//        val savedEventsStr = sharedPreferences.getString("saved_events_data", "")
//        if (savedEventsStr != null) {
//            if (savedEventsStr.isNotEmpty()) {
//                val eventsList = mutableListOf<DateChoose.Event>()
//                savedEventsStr.split("\n").forEach { eventStr ->
//                    val parts = eventStr.split(",")
//                    if (parts.size == 2) {
//                        val date = parts[0]
//                        val calories = parts[1].toIntOrNull()
//                        if (date.isNotBlank() && calories != null) {
//                            eventsList.add(DateChoose.Event(date, calories))
//                        }
//                    }
//                }
//                eventDataList = eventsList
//            }
//        }
//    }

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_event_details)
        btnGoToCalendar = findViewById(R.id.buttonEdit)
        btnBeginTimePicker = findViewById(R.id.btnBeginTimePicker)
        btnEndTimePicker = findViewById(R.id.btnEndTimePicker)
        tvBeginTime = findViewById(R.id.BeginTime)
        tvEndTime = findViewById(R.id.EndTime)
        graph = findViewById(R.id.graph) as GraphView
        btnBeginTimePicker.setOnClickListener { showTimePicker(tvBeginTime) }
        btnEndTimePicker.setOnClickListener { showTimePicker(tvEndTime) }

        val receivedDataList = intent.getParcelableArrayListExtra<DateChoose.Event>("events_data")
        val dates: MutableList<String> = ArrayList()
        val calories: MutableList<Double> = ArrayList()

        for (event in receivedDataList!!) {
            val dateString = event.date // 假设getDate()返回格式化的日期字符串
            val calorieValue = event.calories // 假设getCalories()返回整型或Double类型的卡路里值
            dates.add(dateString)
            calories.add(calorieValue.toDouble())
        }
        check(dates.size == calories.size)
        val dataPoints = calories.withIndex().map { (index, value) ->
            DataPoint(index.toDouble(), value)
        }.toTypedArray()


        btnGoToCalendar.setOnClickListener {
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
        }
//        loadEventDataFromPreferences()
//        val dates1 = listOf("2023-04-01", "2023-04-02","2023-04-02" , "2023-04-30","2023-04-02") //测试数据
//        val dataPoints = dates.zip(calories).withIndex().map { (index, pair) ->
//            val (dateStr, value) = pair
//            DataPoint(index.toDouble(), value).apply {
//
//            }
//        }
//
//        val series = LineGraphSeries(dataPoints.toTypedArray())

        val series = LineGraphSeries(dataPoints)
//        val series = LineGraphSeries(
//            arrayOf(
//                DataPoint(0.0, calories[0]),
//                DataPoint(1.0, calories[1]),
//                DataPoint(2.0, calories[2]),
//                DataPoint(3.0, calories[3])
//            )
//        )

        series.thickness = 3 // 设置线条粗细
        graph.addSeries(series)
        graph.viewport.isXAxisBoundsManual = true
        val renderer: GridLabelRenderer = graph.getGridLabelRenderer()
        renderer.setHorizontalLabelsAngle(90)
        // 自定义X轴标签为对应的日期
        graph.getGridLabelRenderer().setLabelFormatter(object : LabelFormatter {
            override fun formatLabel(value: Double, isValueX: Boolean): String {
                return if (isValueX) {
                    val dateIndex = value.toInt()
                    if (dateIndex in dates.indices) {
                        dates[dateIndex]
                    } else {
                        "超出范围" // 或者处理索引超出范围的情况
                    }
                } else {
                    // 适当的纵坐标标签格式，例如保留两位小数
                    "%.2f".format(value)
                }
            }
            override fun setViewport(viewport: Viewport?) {
            }
        })


    }

}